<?php

namespace addons\qingdongams\model;

use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 * 商机管理
 */
class Business Extends Model
{
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'qingdongams_business';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    //创建商机
    public static function createBusiness($params) {
        //自定义字段
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name, 'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
                unset($params[$name]);
            }else{
                if(empty($params[$name])){
                    $params[$name]=NULL;
                }
            }
        }
        $product = [];
        if (isset($params['product']) && $params['product']) {
            $product = $params['product'];
            unset($params['product']);
            foreach ($product as $tkey => $t) {
                unset($product[$tkey]['id']);
                if($t['number'] <=0){
                    throw new Exception('产品数量必须大于0');
                }

            }
        }
        $customer=Customer::where(['id'=>$params['customer_id']])->find();
        if(empty($customer)){
            throw new Exception('客户不存在');
        }
        $params['owner_staff_id'] = $customer->owner_staff_id;

        $staff = Staff::info();
        if (!empty($staff)) {
            $params['create_staff_id'] = $staff->id;
        }

        $Model = new self;
        $result = $Model->allowField(true)->save($params);

        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($Model->getError());
        }

        $lastId     = $Model->id;
        $otherModel = new BusinessOther();
        if ($otherModel->save(['id' => $lastId, 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
            // 验证失败 输出错误信息
            throw new Exception($otherModel->getError());
        }


        $addProduct = [];
        foreach ($product as $v) {
            $v['business_id'] = $lastId;
            $addProduct[]     = $v;
        }

        if ($addProduct) {
            $productModel = new BusinessProduct();
            $productModel->allowField(true)->saveAll($addProduct);
        }

        OperationLog::createLog(OperationLog::BUSINESS_TYPE, $lastId, '创建商机');

        return true;
    }


    //修改商机
    public static function updateBusiness($params) {
        //自定义字段
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name, 'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
                unset($params[$name]);
            }else{
                if(empty($params[$name])){
                    $params[$name]=NULL;
                }
            }
        }
        $product = [];

        if (isset($params['product'])) {
            $product = $params['product'];
            unset($params['product']);
            if(isset($params['row[product'])){
                unset($params['row[product']);
            }
            if(!is_array($product)){
                $product = json_decode($product,true);
            }
            foreach ($product as $tkey => $t) {
                unset($product[$tkey]['id']);
                if($t['number'] <=0){
                    throw new Exception('产品数量必须大于0');
                }
            }
        }
        $Model                  = new self;

        // 调用当前模型对应的User验证器类进行数据验证
        $result = $Model->allowField(true)->save($params, ['id' => $params['id']]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($Model->getError());
        }


        $otherModel = new BusinessOther();
        if ($otherModel->save(['otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)], ['id' => $params['id']]) === false) {
            // 验证失败 输出错误信息
            throw new Exception($otherModel->getError());
        }


        $addProduct = [];
        if($product){
            foreach ($product as $v) {
                $v['business_id'] = $params['id'];
                $addProduct[]     = $v;
            }
        }

        if ($addProduct) {
            $productModel = new BusinessProduct();
            $productModel->where(['business_id' => $params['id']])->delete();
            $productModel->allowField(true)->saveAll($addProduct);
        }


        return true;
    }


    //获取更新时间
    public function getUpdatetimeAttr($value) {
        return date('Y-m-d H:i:s', $value);
    }


    //负责人
    public function ownerStaff() {
        return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img');
    }


    //客户
    public function customer() {
        return $this->hasOne(Customer::class, 'id', 'customer_id')->field('id,name,follow');
    }
    //商机
    public function businessOther() {
        return $this->hasOne(BusinessOther::class, 'id', 'id');
    }

    //
    public function staff() {
        return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img,department_id,post');
    }

//产品
    public function product(){
        return $this->hasMany(BusinessProduct::class,'business_id','id')->with('productOne');
    }
    /**
     * 批量转移商机
     */
    public static function batchTransfer($ids, $staff_id) {
        Db::startTrans();
        try {
            if (Business::where(['id' => ['in',$ids]])->update([
                    'owner_staff_id' => $staff_id,
                    'updatetime'     => time()
                ]) == false) {
                throw new Exception('修改失败');
            }

            $staff = Staff::get($staff_id);
            foreach ($ids as $id){
                OperationLog::createLog(OperationLog::BUSINESS_TYPE, $id, '将商机转移给：' . $staff['name']);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }

        return true;
    }

    public static function getList() {
        return self::where(['owner_staff_id'=>['in',Staff::getMyStaffIds()]])->field('id,name')->select();
    }
    /**
     * 推进商机
     */
    public static function batchStatus($params) {
        Db::startTrans();
        try {
            (new self())->save(['status'=>$params['type']],['id'=>$params['id']]);
            $ret = array(
                'business_id'=>$params['id'],
                'type'=>$params['type'],
                'remark'=>$params['remark'],
                'file'=>$params['file'],
            );
            $result = BusinessStatus::create($ret);
            if ($result == false) {
                throw new Exception('推进失败');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }

        return true;
    }

    /**
     * 导入商机
     * @param $data
     * @return bool
     */
    public static function importBusiness($data) {
        $addBusiness = [];
        $addOther     = [];
        $addLog=[];
        foreach ($data as $params) {
            //自定义字段
            $other = [];
            foreach ($params as $name => $val) {
                if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
                    unset($params[$name]);
                }else{
                    if(empty($params[$name])){
                        $params[$name]=NULL;
                    }
                }
            }
            $other['id']           = $params['id'];
            $params['next_time']   = date('Y-m-d H:i:s');
            $params['createtime'] = time();
            $params['updatetime'] = time();
            $addOther[]            = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
            $addLog[] = [
                'content'        => '导入商机',
                'operation_type' => 2,
                'operation_id'   => 30,
                'relation_type'  => OperationLog::BUSINESS_TYPE,
                'relation_id'    => $params['id'],
                'createtime'     => time()
            ];
            $addBusiness[]        = $params;
        }

        $customer = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $customer->allowField(true)->insertAll($addBusiness);

        $otherModel = new BusinessOther();
        $otherModel->allowField(true)->insertAll($addOther);

        $logModel = new OperationLog();
        $logModel->allowField(true)->insertAll($addLog);

        return true;
    }

}